package com.starlight.flower_server.domain.service.cart.impl;

import com.starlight.flower_server.controller.exception.NotFoundException;
import com.starlight.flower_server.domain.cart.data.CartData;
import com.starlight.flower_server.domain.service.cart.CartService;
import com.starlight.flower_server.infrastructure.Status;
import com.starlight.flower_server.infrastructure.entity.cart.Cart;
import com.starlight.flower_server.infrastructure.entity.cart.CartItem;
import com.starlight.flower_server.infrastructure.util.CurrentUserInfoUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author yfy2001
 * @date 2023/5/19 12:45
 */
@Service
public class CartServiceImpl implements CartService {

    @Resource
    private RedisTemplate<Long, Cart> redisTemplate;


    @Override
    public CartData getDetail() {
        Long userId= Long.valueOf(CurrentUserInfoUtils.getUserId());
        Cart cart=redisTemplate.opsForValue().get(userId);
        if(cart==null){
            return null;
        }
        CartData cartData=new CartData();
        BeanUtils.copyProperties(cart,cartData);
        return cartData;
    }

    @Override
    public Cart getCart() {
        Long userId= Long.valueOf(CurrentUserInfoUtils.getUserId());
        return redisTemplate.opsForValue().get(userId);
    }

    @Override
    public Boolean addItem(CartItem cartItem) {
        Long userId= Long.valueOf(CurrentUserInfoUtils.getUserId());
        Cart cart=redisTemplate.opsForValue().get(userId);
        if (cart==null){
            cart=createCart();
        }
        Map<Long, CartItem> cartItemMap=cart.getItemMap();
        cartItemMap.put(userId,cartItem);
        cart.setItemMap(cartItemMap);
        redisTemplate.opsForValue().set(userId,cart,30,TimeUnit.DAYS);
        return true;
    }

    @Override
    public Boolean removeItem(Long itemId) {
        Long userId= Long.valueOf(CurrentUserInfoUtils.getUserId());
        Cart cart=redisTemplate.opsForValue().get(userId);
        if (cart==null){
            throw new NotFoundException(Status.CART_NOT_FOUND.getMessage(),Status.CART_NOT_FOUND);
        }
        Map<Long, CartItem> cartItemMap=cart.getItemMap();
        cartItemMap.remove(itemId);
        cart.setItemMap(cartItemMap);
        redisTemplate.opsForValue().set(userId,cart,30,TimeUnit.DAYS);
        return true;
    }

    @Override
    public Cart createCart() {
        Long userId= Long.valueOf(CurrentUserInfoUtils.getUserId());
        Cart cart=new Cart();
        cart.setCreated(new Date());
        redisTemplate.opsForValue().set(userId,cart,30,TimeUnit.DAYS);
        return cart;
    }
}
